package cn.tedu.egvehicle1.controller;

import cn.tedu.egvehicle1.base.response.JsonResult;
import cn.tedu.egvehicle1.base.utils.CacheUtil;
import cn.tedu.egvehicle1.mapper.NoticeMapper;
import cn.tedu.egvehicle1.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/v1/notice/")
@Api("03.公告管理模块")
@Slf4j
public class NoticeController {
    @Autowired
     public NoticeMapper noticeMapper;

    /*
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    */

    @Autowired
    private CacheUtil cacheUtil;


    @GetMapping("list")
    @ApiOperation("首页公告展示")
    @ApiOperationSupport(order = 10)
    public JsonResult list(){
         /*
            设计Redis中的key-value：{"vehicle_index":'{"data":...}'}
            1.确认缓存[Redis]中是否存在响应数据 GET key；
            2.缓存中存在，直接返回结束；
            3.缓存中不存在
                3.1 到MySQL中查询响应数据；
                3.2 将响应的数据缓存到Redis中  SET key value；
                3.3 返回结束
         */
        // ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable index =cacheUtil.get("vehicle_index");

        if(index != null){
            System.out.println("首页数据来自于Redis数据库...");

            return JsonResult.success(index);
        }else {
            List<NoticeListVO> noticeListVOS = noticeMapper.selectNotice();

            cacheUtil.setExpire("vehicle_index",(Serializable) noticeListVOS,30);

            System.out.println("首页数据来自于MySQL数据库...");
            return JsonResult.success(noticeListVOS);
        }
    }
}
